#import "QualityGoodsMainViewController.h"
#import "HandleData.h"
#import <UIImageView+WebCache.h>
#import "Banner.h"
#import "Topic.h"
#import "TopicTableViewCell.h"
#import <MJRefresh.h>
#import "QuanlityBannerViewController.h"
#import "QuanlityOtherBannderViewController.h"
#import "QuanlityViewController.h"
#import "QuanlitySeartchViewController.h"
#define width self.view.bounds.size.width
#define heigh self.view.bounds.size.height

@interface QualityGoodsMainViewController ()<UITableViewDataSource, UITableViewDelegate , UIScrollViewDelegate>
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSMutableArray *bannerArr;
@property (nonatomic, strong) NSMutableArray *topicArr;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, assign)NSInteger pageTimer;
@property (nonatomic, strong)NSTimer *timer;

@end

@implementation QualityGoodsMainViewController

- (void)viewWillAppear:(BOOL)animated
{
     self.tabBarController.tabBar.hidden = NO;
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"isWhite"]) {
        self.tableView.backgroundColor = [UIColor grayColor];
       self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    }else
    {
        self.tableView.backgroundColor = [UIColor whiteColor];
        self.navigationController.navigationBar.barTintColor = [UIColor redColor];

    }
    
    
    [self.tableView reloadData];
    
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
     [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    
    
    self.page = 0;
    
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
//    分界线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableView registerClass:[TopicTableViewCell class] forCellReuseIdentifier:@"topic"];

    self.tableView.showsVerticalScrollIndicator = NO;
    
//      下拉刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self lastValue];
    }];
    
    self.tableView.header = header;

//     马上进入刷新
    [self.tableView.header beginRefreshing];
    
//     上拉加载
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self upValue];
    }];
    
    self.tableView.footer = footer;
    
   
 
    [self addTimer];
    
 

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-icon05.png"] style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
    
    
    
}

- (void)searchAction
{
    QuanlitySeartchViewController *search = [[QuanlitySeartchViewController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
}




- (void)lastValue
{
    NSString *str = @"http://open4.bantangapp.com/recommend/index?client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=1115876&oauth_token=08e623418ebf12fe438fb9eed5d176da&track_deviceid=864516020760583&track_device_info=SM701&channel_name=UMENG_CHANNEL&app_installtime=1438818737013&app_versions=4.1.1&os_versions=4.4.2&screensize=1080&v=6&oauth_token=08e623418ebf12fe438fb9eed5d176da&screensize=1080&page=0&pagesize=20&category=";
    
    [HandleData handleDataWithUrl:str completion:^(id data) {
        NSArray *bannerArr = [[data objectForKey:@"data"] objectForKey:@"banner"];
        NSArray *topicArr = [[data objectForKey:@"data"] objectForKey:@"topic"];
        self.bannerArr = [NSMutableArray array];
        for (NSDictionary *dic in bannerArr) {
            Banner *banner = [[Banner alloc] init];
            [banner setValuesForKeysWithDictionary:dic];
            [self.bannerArr addObject:banner];
        }
        
        id firstImage = [self.bannerArr firstObject];
        id lastImage = [self.bannerArr lastObject];
        
        
        [self.bannerArr addObject:firstImage];
        [self.bannerArr insertObject:lastImage atIndex:0];
        
        self.topicArr = [NSMutableArray array];
        for (NSDictionary *dic in topicArr) {
            Topic *topic = [[Topic alloc] init];
            [topic setValuesForKeysWithDictionary:dic];
            [self.topicArr addObject:topic];
            
        }
        
        [self.tableView reloadData];
        [self bannerAction];
        [self.tableView.header endRefreshing];
        
        
        
    }];
    
}








- (void)upValue
{
    
    self.page ++;
    NSString *str = [NSString stringWithFormat:@"http://open4.bantangapp.com/recommend/index?client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=1115876&oauth_token=08e623418ebf12fe438fb9eed5d176da&track_deviceid=864516020760583&track_device_info=SM701&channel_name=UMENG_CHANNEL&app_installtime=1438818737013&app_versions=4.1.1&os_versions=4.4.2&screensize=1080&v=6&oauth_token=08e623418ebf12fe438fb9eed5d176da&screensize=1080&page=%ld&pagesize=20&category=", self.page];
    
    [HandleData handleDataWithUrl:str completion:^(id data) {
          NSArray *topicArr = [[data objectForKey:@"data"] objectForKey:@"topic"];
        for (NSDictionary *dic in topicArr) {
            Topic *topic = [[Topic alloc] init];
            [topic setValuesForKeysWithDictionary:dic];
            [self.topicArr addObject:topic];
            
        }
        
        [self.tableView reloadData];
        [self.tableView.footer endRefreshing];

    }];
    
}

- (void)addTimer
{
    //    NSLog(@"调用定时器方法");
   
     NSInteger i = self.scrollView.contentOffset.x / width;
    self.pageTimer = i;
    
    
    self.timer = [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    //线程阻塞
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timerAction
{
    //    NSLog(@"启动定时器");
    //    NSLog(@"page = %ld",_pageTimer);
    self.pageTimer ++;
    if (self.pageTimer == self.bannerArr.count - 1) {
        self.pageTimer = 1;
    }
    CATransition *ani = [CATransition animation];
    ani.duration = 1;
    ani.type = @"rippleEffect";
    
    [self.scrollView.layer addAnimation:ani forKey:nil];

    
    [self.scrollView setContentOffset:CGPointMake(width* _pageTimer, 0) animated:NO];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.timer invalidate];
}

- (void)bannerAction
{
    //    轮播图
    
    UIView *cView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, heigh / 3.5)];
    
    self.tableView.tableHeaderView = cView;
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, width, heigh / 3.5)];
    
    self.scrollView.backgroundColor = [UIColor whiteColor];
    [self.tableView addSubview:cView];
    [cView addSubview:self.scrollView];
    
    self.scrollView.contentSize = CGSizeMake(self.bannerArr.count  * width, 0);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.delegate = self;
    
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, heigh / 4.2, width, heigh / 16.675)];
    self.pageControl.numberOfPages = self.bannerArr.count - 2;
    [self.pageControl addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
    [cView addSubview:self.pageControl];
    self.scrollView.contentOffset = CGPointMake(width, 0);
    
    
    for (NSInteger i = 0; i < self.bannerArr.count; i++) {
        UIImageView *picInhead = [[UIImageView alloc] initWithFrame:CGRectMake(i *width, 0, width, heigh / 3.335)];
        Banner *banner = [self.bannerArr objectAtIndex:i];
        [picInhead sd_setImageWithURL:[NSURL URLWithString:banner.photo] placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
        [self.scrollView addSubview:picInhead];
     
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        picInhead.userInteractionEnabled = YES;
        [tap addTarget:self action:@selector(tapAction:)];
        [picInhead addGestureRecognizer:tap];
 
        
    }
    
}

- (void)tapAction:(UIGestureRecognizer *)tap
{
    NSInteger i = self.scrollView.contentOffset.x / width;
    Banner *banner = [self.bannerArr objectAtIndex:i];
    
    if ([banner.type isEqualToString:@"webview"]) {
        
    QuanlityBannerViewController *bannerVC = [[QuanlityBannerViewController alloc] init];
    [self.navigationController pushViewController:bannerVC animated:YES];
    
    bannerVC.banner = banner;
    }else
    {
        QuanlityOtherBannderViewController *otherBannerVC = [[QuanlityOtherBannderViewController alloc] init];
        [self.navigationController pushViewController:otherBannerVC animated:YES];
        
        otherBannerVC.banner = banner;
        
    }

}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self addTimer];
    if (self.scrollView.contentOffset.x > width * (self.bannerArr.count - 2)) {
        [self.scrollView setContentOffset:CGPointMake(width, 0) animated:NO];
        
    }
    
    if (self.scrollView.contentOffset.x < width) {
        [self.scrollView setContentOffset:CGPointMake(width * (self.bannerArr.count - 2), 0) animated:NO];
    }
}




- (void)pageAction:(UIPageControl *)page
{
    [self.scrollView setContentOffset:CGPointMake(page.currentPage * width, 0) animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.pageControl.currentPage = (scrollView.contentOffset.x - width) / width;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.topicArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        TopicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"topic"];
    cell.backgroundColor = [UIColor clearColor];
        Topic *topic = [self.topicArr objectAtIndex:indexPath.row];
    
    
        cell.title.text = topic.title;
        [cell.pic sd_setImageWithURL:[NSURL URLWithString:topic.pic] placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
        cell.likes.text = topic.likes;
 
   

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return heigh / 4;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    QuanlityViewController *quanLityVC = [[QuanlityViewController alloc] init];
    [self.navigationController pushViewController:quanLityVC animated:YES];
    
    Topic *topic = [self.topicArr objectAtIndex:indexPath.row] ;
    
    quanLityVC.ID = topic.ID;
    quanLityVC.topic = [self.topicArr objectAtIndex:indexPath.row];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
